
package com.yunqiao.api.controller;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.util.Base64;
import com.yunqiao.common.exception.CustomApiException;
import com.yunqiao.common.utils.ApiResponse;
import com.yunqiao.common.utils.ConfigConstant;
import com.yunqiao.service.oss.SysOssService;
import com.yunqiao.service.oss.cloud.OSSFactory;
import com.yunqiao.service.oss.entity.SysOssEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 文件上传
 *
 * @author Crocutax
 * @email wangxw725@163.com
 * @date 2017-03-25 12:13:26
 */
@RestController
@RequestMapping("api/oss")
@Api(tags = "OssApiController" ,description = "文件上传")
public class OssApiController {

	@Autowired
	private SysOssService sysOssService;

    private final static String KEY = ConfigConstant.CLOUD_STORAGE_CONFIG_KEY;

	/**
	 * 上传文件
	 */
	@PostMapping("/upload")
    @ApiOperation("上传单个文件")
	public ApiResponse upload(@RequestParam("file") MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			throw new CustomApiException("上传文件不能为空");
		}
		//上传文件
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);

		//保存文件信息
		SysOssEntity ossEntity = new SysOssEntity();
		ossEntity.setUrl(url);
		ossEntity.setCreateDate(new Date());
		sysOssService.save(ossEntity);

		return new ApiResponse(url);
	}

    @ApiImplicitParam(name = "fileBase64", value = "base64文件", required = true ,paramType = "query" , dataType = "String")
	@PostMapping("/base64Upload")
    @ApiOperation("base64格式上传单个文件")
	public ApiResponse base64Upload(@RequestBody Map param) throws Exception {
	    String fileBase64 = MapUtil.getStr(param, "fileBase64");
        if (StringUtils.isEmpty(fileBase64)) {
            throw new NullPointerException("fileBase64 不能为null");
        } else {
            fileBase64 = fileBase64.replaceFirst("data:image/png;base64,", "");
            String classDir = this.getClass().getResource("/").getPath();
            String tempPath = classDir + "/" + System.currentTimeMillis() + ".png";
            byte[] byteimg = Base64.decodeFast(fileBase64.trim());
            for (int i = 0; i < byteimg.length; ++i) {
                if (byteimg[i] < 0) {// 调整异常数据
                    byteimg[i] += 256;
                }
            }

            String url = OSSFactory.build().uploadSuffix(byteimg, ".png");
            /*FileOutputStream fos = new FileOutputStream(tempPath);
            fos.write(byteimg);
            fos.flush();
            fos.close();*/

            //保存文件信息
            SysOssEntity ossEntity = new SysOssEntity();
            ossEntity.setUrl(url);
            ossEntity.setCreateDate(new Date());
            sysOssService.save(ossEntity);

            return new ApiResponse(url);

        }
    }

    /**
     * 获取文件宽高
     */
    @PostMapping("/getUploadWidthHeight")
    @ApiOperation("获取文件宽高")
    public ApiResponse getUploadWidthHeight(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new CustomApiException("上传文件不能为空");
        }
        BufferedImage read = ImageIO.read(file.getInputStream());
        int width = read.getWidth();
        int height = read.getHeight();

        int minTileX = read.getTileGridXOffset();
        int minTileY = read.getTileGridYOffset();
        Dict dict = Dict.create()
            .set("width", width)
            .set("height", height)
            .set("minTileX", minTileX)
            .set("minTileY", minTileY)

            ;

        return new ApiResponse(dict);
    }

    private String replacePre(String imgString) {
        //允许的图片格式（可配置）
        String imgType = "jpg,png,jpeg";
        if (!StringUtils.isEmpty(imgType)) {
            String[] imgTypes = imgType.split(",");
            Pattern pattern;
            Matcher matcher;
            String regex;
            for (String v : imgTypes) {
                regex = MessageFormat.format("data:image/{0};base64,", v);
                pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
                matcher = pattern.matcher(imgString);
                if (matcher.lookingAt()) {
                    return matcher.replaceFirst("");
                }
            }
        }
        return imgString;
    }
}
